﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CloudPms.Domain.Repository
{
    public class SQLParametersValidate
    {
        /// <summary>
        /// 检测是否含有危险字符（防止Sql注入）
        /// </summary>
        /// <param name="content">预检测的内容</param>
        /// <returns>返回True或false</returns>
        public static bool HasDangerousWord(string content)
        {
            if (content.Length > 0)
            {
                //convert to lower
                string sLowerStr = content.ToLower();

                //RegularExpressions
                const string sRxStr = @"(/sand/s)|(/sand/s)|(/slike/s)|(select/s)|(insert/s)|(delete/s)|(update/s[/s/S].*/sset)|(create/s)|(/stable)|(<[iframe|/iframe|script|/script])|(')|(/sexec)|(/sdeclare)|(/struncate)|(/smaster)|(/sbackup)|(/smid)|(/scount)";

                var sRx = new System.Text.RegularExpressions.Regex(sRxStr);

                if (sRx.IsMatch(sLowerStr, 0))
                {
                    return true;
                }
            }
            return false;
        }

        public static bool HasDangerousWord(string[] contents)
        {
            if(contents.Length>0)
            {
                return contents.Any(HasDangerousWord);
            }
            return false;
        }

        /// <summary>
        /// 替换掉危险的字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static String ReplaceDangerous(string str)
        {
            if (string.IsNullOrWhiteSpace(str)) return str;

            str = str.Replace(";", "");
            str = str.Replace("&", "&amp;");
            str = str.Replace("<", "&lt;");
            str = str.Replace(">", "&gt;");
            str = str.Replace("'", "");
            str = str.Replace("--", "");
            str = str.Replace("/", "");
            str = str.Replace("%", "");
            return str;
        }
        
    }
}
